const express = require('express')
const router = express.Router()
const jwt = require('jsonwebtoken')
const multipart = require('../../middleware/content-type/multypart')
const { insertUser, checkUserLogin, modifyUserPassword } = require('../../model/mongo')
const fs = require('fs')
const path = require('path')

router.use(multipart())

router.post('/regist', async (req, res) => {
    const result = {
        code: 200,
        msg: '注册成功'
    }
    try {
        result.msg = await insertUser(req.body)
    } catch (err) {
        result.msg = err
        result.code = 400
    }
    res.send(JSON.stringify(result))
})

router.post('/login', async (req, res) => {
    const private_key = fs.readFileSync(path.join(__dirname, '../../key/rsa_private_key.pem'))
    const result = {
        code: 200,
        msg: '登录成功',
        data: {}
    }
    try {
        let { userid, freeze } = await checkUserLogin(req.body)
        result.data.userid = userid
        result.data.freeze = freeze
        result.data.token = jwt.sign(req.body, private_key, { algorithm: 'RS256' })
    } catch (err) {
        result.code = 400
        result.msg = err
    }
    res.send(JSON.stringify(result))
})

router.post('/modify', async (req, res) => {
    let { userid, password } = req.body
    let result = {
        code: 200
    }
    result.msg = await modifyUserPassword(userid, password)
    res.send(JSON.stringify(result))
})

module.exports = router
